import React, { Component } from 'react';
import { NavBar, Card, TextareaItem, WhiteSpace, WingBlank, Flex, Toast,ImagePicker  } from 'antd-mobile'
import { Formik } from 'formik';
import '../../css/appraisal.css'
import { getPartyDetail, postAppraisal,postImage } from '../../api/index'

import DateUtil from "../../util/DateUtil";
import {setImageById} from '../../util/imageUtil'
import { array } from 'js-md5';
interface Props {
  history?: any;
  location?: any,
  match?: any
}
interface State {
  starInfo: string,
  party: any,
  user: any,
  files:any,
  image:any
}

async function uploadImage(param:any){
  return postImage(param) 
}


async function fileAction (array:any) {
   return new Promise(async resolve=>{
    const imageList=array;
    let resultList = []
    if(imageList.length>0){
         for(let i=0;i<imageList.length;i++){
           const item = imageList[i]
           let result =  await uploadImage({name:item.file.name,content:item.url});
           resultList.push(result)
         }
     
    }
    resolve(resultList)
  })
}

class MyComponent extends Component<Props, State>   {
  constructor(props: Props) {
    super(props);
    this.state = {
      starInfo: '',
      party: {},
      user: {},
      files:[],
      image:''
    }

  }
  componentDidMount() {
    const { history, match: { params } } = this.props;
    const userJSONStr = sessionStorage.getItem('user') || '';
    const barcode: any = sessionStorage.getItem('barcode');
    const than = this
    if (!!params.partyId && !!params.reserveId && !!userJSONStr) {
      getPartyDetail({ barcode: barcode, id: params.partyId }).then((response: any) => {
        const { data: { party } } = response
        let user = JSON.parse(userJSONStr);
        than.setState({
          party,
          user
        })
        setImageById(party.imageId).then(image=>{
          this.setState({image})
        })
      }).catch(e => {

      })
    } else {
      history.push('/');
    }
  }
  commit = (values: any) => {
    Toast.loading('正在提交评价...', 10)
    const { history, match: { params } } = this.props;
    const { files } = this.state;
    if (!values.score) {
      Toast.fail('请评分!');
      return false;
    }
    if (!values.appraisal) {
      Toast.fail('请填写评论内容!');
      return false;
    }
    let user = this.state.user;
    let party = this.state.party;
    let readerReserveGroup = [
      {
        barcode: user.barcode,
        name: `${user.personal.firstName} ${user.personal.lastName}`,
        mobilePhone: user.personal.mobilePhone,
      },
    ];
    let requestParams = {
      readerReserveGroup,
      propertyName: party.propertyName,
      partyId: party.id,
      partyImageId:party.imageId,
      reserveId: params.reserveId,
      partyName: party.partyName,
      partyStartDate: party.partyStartDate,
      state: 0,
      score: values.score,
      appraisal: values.appraisal
    }
    
    fileAction(files).then((response:any)=>{
      debugger
      let imageIdList:any = []
      if(response.length >0){
        response.forEach((item:any)=>{
         imageIdList.push(item.data.id)
        })
      }
      let postParam = {
        imageIdList,
        ...requestParams 
     }
 
        postAppraisal(postParam).then((res) => {
            setTimeout(() => {
              Toast.hide()
              Toast.success('评价成功', 1.5, () => {
                history.push('/');
              })
            }, 1500)
          })
    })
   

  }
  onChange = (files:any, type:any, index:any) => {
   this.setState({
      files,
    });
  };
  render() {
    const then = this
    const { history } = this.props
    const { files } = this.state;
    return (
      <div className="container">
        <NavBar style={{ backgroundColor: "white", color: "black", boxShadow: '1px 1px 3px 1px #7773' }}>活动评价</NavBar>
        <Formik
          initialValues={{ score: 0, appraisal: '' }}
          onSubmit={(values, actions) => {
            then.commit(values);
          }}
          render={(p) => (
            <form onSubmit={p.handleSubmit}>
              <WingBlank size="md">
                <WhiteSpace size={'lg'} />
                <Card>
                 <Card.Body>
                 <Flex>
                     <Flex.Item style={{maxWidth:130}}> <img src={this.state.image} style={{width:130,height:88}}></img></Flex.Item>
                     <Flex.Item> 
                     <div className="act-t">
                    <div className="activity-hint clearfix">
                      <span style={{ fontSize: '18px' }} 
                       onClick={() => {
                        history.push(`/party_details/${this.state.party.principalId}`);
                    }}
                      >{this.state.party.partyName}</span>
                    </div>
                  </div>
                  <div className="act-t">
                    <div className="activity-hint clearfix">
                   
                      <span className={'font'}>
                        {DateUtil.mergeFormat(this.state.party.partyStartDate, this.state.party.partyEndDate)}
                      </span>
                    </div>
                  </div>
                     </Flex.Item>
                 </Flex>
                </Card.Body>
                  
               </Card>
             
                <WhiteSpace size={'lg'} />
                <Card>
                  <Card.Header
                    title={(
                      <Flex>
                        <div style={{marginBottom:50}}>评价&nbsp;<span style={{ color: 'red' }}>*</span>：</div>
                        <div className="panel-body" style={{marginTop:50}}>
                          <div className="starability-container">
                            <fieldset className="starability-slot">
                              <input type="radio" id="rate_1_0_1_5" name="score" onClick={() => {
                                p.setFieldValue('score', 5)
                                
                              }} />
                              <label htmlFor="rate_1_0_1_5" title="5星"></label>
                              <input type="radio" id="rate_1_0_1_4" name="score" onClick={() => {
                                p.setFieldValue('score', 4)
                               
                              }} />
                              <label htmlFor="rate_1_0_1_4" title="4星"></label>
                              <input type="radio" id="rate_1_0_1_3" name="score" onClick={() => {
                                p.setFieldValue('score', 3)
                                then.setState({
                                  starInfo: ''
                                })
                              }} />
                              <label htmlFor="rate_1_0_1_3" title="3星"></label>
                              <input type="radio" id="rate_1_0_1_2" name="score" onClick={() => {
                                p.setFieldValue('score', 2)
                                 
                              }} />
                              <label htmlFor="rate_1_0_1_2" title="2星"></label>
                              <input type="radio" id="rate_1_0_1_1" name="score" onClick={() => {
                                p.setFieldValue('score', 1);
                                
                              }} />
                              <label htmlFor="rate_1_0_1_1" title="1星"></label>
                            </fieldset>
                          </div>
                          <span style={{ fontSize: ' .2rem', lineHeight: '0.7rem', padding: '.3rem', fontStyle: 'oblique' }}
                            id="starStr">{this.state.starInfo}</span>
                        </div>
                      </Flex>
                    )}

                  />
                  <Card.Body>
                    <TextareaItem
                      placeholder={"请输入详细说明"}
                      autoHeight
                      onChange={(val: string | undefined) => {
                        if (!!!val) {
                          p.setFieldValue('appraisal', '')
                        } else {
                          p.setFieldValue('appraisal', val)
                        }
                      }}
                      rows={5}
                      count={200}
                      name={'appraisal'}
                      defaultValue={p.values.appraisal}
                    />
                  </Card.Body>

                </Card>
                <WingBlank size={'lg'}  >
                <div style={{height:15}}>
                    <div style={{float:'left'}}>上传图片</div>
                    <div style={{float:'right',color:'#ccc'}}>图片{files.length}/5</div>
                </div>
                </WingBlank> 
                <ImagePicker
                   length="3"
                   files={files}
                   onChange={this.onChange}
                   selectable={files.length < 5}
             />
                <input type="submit" className="weixin-btn" value="发布评价" style={{ width: '100%' }} />
                <input
                  type="button"
                  className="weixin-btn-goback"
                  value="返回"
                  style={{ width: '100%' }}
                  onClick={() => {
                    history.push('/');
                  }}
                />
              </WingBlank>
            </form>
          )}></Formik>
      </div>
    );
  }
}


export default MyComponent;
